#import "NoticeDetailViewController.h"
#import "ScreenAdapter.h"
#import "SDWebImageManager.h"

#define PADDING 15

@interface NoticeDetailViewController ()

@end

@implementation NoticeDetailViewController
@synthesize myScrollView, my_dict, imageview_array, mw_url_array;

-(void)viewWillAppear:(BOOL)animated
{
    self.navigationItem.title=@"通知详情";
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 20 , 44, 44)];
    button.showsTouchWhenHighlighted = YES;
    button.backgroundColor = [UIColor clearColor];
    button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 30);
    [button setImage:[UIImage imageNamed:@"nav_btn_back"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backButton:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@""
                                   style:UIBarButtonItemStylePlain
                                   target:nil
                                   action:nil];
    self.navigationItem.backBarButtonItem=backButton;
    
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
        self.edgesForExtendedLayout = UIRectEdgeNone;
}
-(void)backButton:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (UIStatusBarStyle) preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    ScreenAdapter *sa = [ScreenAdapter getInstanse];
    
    // Do any additional setup after loading the view from its nib.
    
    //创建标题
    UILabel *title_lable = [[UILabel alloc]init];
    title_lable.text = [my_dict objectForKey:@"title"];
    title_lable.numberOfLines = 0;
    title_lable.font = [UIFont systemFontOfSize:16];
    title_lable.textColor = UIColorMake(45, 45, 45);
    CGFloat title_width = sa.screenWidth - PADDING * 2;
    CGSize textSize =  [self sizeWithString:[my_dict objectForKey:@"title"] font:[UIFont systemFontOfSize:15] maxSize:CGSizeMake(title_width, MAXFLOAT)];
    CGFloat title_height = textSize.height;
    
    title_lable.frame = CGRectMake(PADDING, PADDING, title_width, title_height);
    
    [myScrollView addSubview:title_lable];
    
    //创建时间戳
    UILabel *timestamp_lable = [[UILabel alloc]init];
    timestamp_lable.text = [my_dict objectForKey:@"timestamp"];
    timestamp_lable.numberOfLines = 0;
    timestamp_lable.font = [UIFont systemFontOfSize:12];
    timestamp_lable.textColor = UIColorMake(112, 112, 112);
    CGFloat timestamp_width = sa.screenWidth - PADDING * 2;
    
    textSize = [self sizeWithString:[my_dict objectForKey:@"timestamp"] font:[UIFont systemFontOfSize:12]                   maxSize:CGSizeMake(timestamp_width, MAXFLOAT)];
    CGFloat timestamp_height = textSize.height;
    
    CGFloat timestamp_y = CGRectGetMaxY(title_lable.frame) + PADDING;
    
    timestamp_lable.frame = CGRectMake(PADDING, timestamp_y, timestamp_width, timestamp_height);
    [myScrollView addSubview:timestamp_lable];
    
    //创建内容text
    UILabel *content_lable = [[UILabel alloc]init];
    NSString *str = [my_dict objectForKey:@"content"];
    
    content_lable.numberOfLines = 0;
    content_lable.font = [UIFont systemFontOfSize:14];
    content_lable.textColor = UIColorMake(112, 112, 112);
    CGFloat content_width = sa.screenWidth - PADDING * 2;
    
    textSize = [self sizeWithString:[my_dict objectForKey:@"content"] font:[UIFont systemFontOfSize:14] maxSize:CGSizeMake(content_width, MAXFLOAT)];
    
    NSInteger lineNumbers = textSize.height/16.666667;
    NSInteger lineSpace = 5;
    if (lineNumbers == 1) {  //当前只有一行的时候，需要设置行间距为0，不然出现bug
        lineSpace = 0;
    }
    CGFloat content_height = textSize.height + (lineNumbers - 1)*lineSpace;

    //设置行间距的代码
    NSMutableAttributedString * attributedString1 = [[NSMutableAttributedString alloc] initWithString:str];
    NSMutableParagraphStyle * paragraphStyle1 = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle1 setLineSpacing:lineSpace];
    [attributedString1 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle1 range:NSMakeRange(0, [str length])];
    [content_lable setAttributedText:attributedString1];
    
    CGFloat content_y = CGRectGetMaxY(timestamp_lable.frame) + PADDING;
    
    content_lable.frame = CGRectMake(PADDING, content_y, content_width, content_height);
    [myScrollView addSubview:content_lable];
    
    CGFloat max_y = CGRectGetMaxY(content_lable.frame) + PADDING;
    content_max_y = max_y;
    
    imageview_array = [NSMutableArray arrayWithCapacity:10];
    mw_url_array = [NSMutableArray arrayWithCapacity:10];
    int temp_index = 0;
    //创建图片集
    NSArray* pics_array = [my_dict objectForKey:@"pics"];
    for (NSString* pics_url in pics_array) {
        [mw_url_array addObject:[MWPhoto photoWithURL:[NSURL URLWithString:pics_url]]];
        
        NSMutableDictionary *size_dict = [NSMutableDictionary dictionaryWithCapacity:5];
        
        UIImageView* imageView = [[UIImageView alloc]initWithFrame:CGRectMake(PADDING, max_y, sa.screenWidth-2*PADDING, sa.screenWidth-2*PADDING)];
        [imageView setImage:[UIImage imageNamed:@"left_bg"]];
        
        UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(PADDING, max_y, sa.screenWidth-2*PADDING, sa.screenWidth-2*PADDING)];
        button.tag = temp_index;
        [button addTarget:self action:@selector(clickImage:) forControlEvents:UIControlEventTouchUpInside];
        
        [size_dict setObject:imageView forKey:@"imageView"];
        [size_dict setObject:button forKey:@"button"];
        
        [imageview_array addObject:size_dict];
        
        max_y = CGRectGetMaxY(imageView.frame) + PADDING;
        
        [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:pics_url] options:SDWebImageLowPriority progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
            CGFloat new_width = sa.screenWidth - 2*PADDING;
            CGFloat ratio = new_width / image.size.width;
            CGFloat new_height = image.size.height * ratio;
                
            [size_dict setObject:image forKey:@"img"];
            [size_dict setObject:[NSNumber numberWithFloat:new_height]  forKey:@"height"];
            [size_dict setObject:[NSNumber numberWithFloat:new_width] forKey:@"width"];
            [self updateImageView];
            
        }];
        [myScrollView addSubview:imageView];
        [myScrollView addSubview:button];
        temp_index++;
    }
    [myScrollView setContentSize:CGSizeMake(sa.screenWidth, max_y)];
}

- (void)updateImageView{
    int my = content_max_y;
    for (NSDictionary* mydict in imageview_array) {
        
        CGFloat width = [[mydict objectForKey:@"width"] floatValue];
        if (width > 1) {
            CGFloat height = [[mydict objectForKey:@"height"] floatValue];
            UIImageView * image_view = (UIImageView*)[mydict objectForKey:@"imageView"];
            image_view.frame = CGRectMake(PADDING, my, width, height);
            
            UIImageView * button = (UIImageView*)[mydict objectForKey:@"button"];
            button.frame = CGRectMake(PADDING, my, width, height);
            
            
            UIImage *image = (UIImage*)[mydict objectForKey:@"img"];
            [image_view setImage:image];
            
            my = CGRectGetMaxY(image_view.frame) + PADDING;
        }else{
            UIImageView * image_view = (UIImageView*)[mydict objectForKey:@"imageView"];
            CGFloat height = image_view.frame.size.height;
            CGFloat width = image_view.frame.size.width;
            image_view.frame = CGRectMake(1, my, width, height);
            
            UIImageView * button = (UIImageView*)[mydict objectForKey:@"button"];
            button.frame = CGRectMake(PADDING, my, width, height);
            
            my = CGRectGetMaxY(image_view.frame) + PADDING;
        }
    }
    [myScrollView setContentSize:CGSizeMake([ScreenAdapter getInstanse].screenWidth, my)];
}

- (void)clickImage:(id)sender{
    UIButton *button = (UIButton*)sender;
    
    // Create browser (must be done each time photo browser is
    // displayed. Photo browser objects cannot be re-used)
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    
    // Set options
    browser.displayActionButton = NO; // Show action button to allow sharing, copying, etc (defaults to YES)
    browser.displayNavArrows = NO; // Whether to display left and right nav arrows on toolbar (defaults to NO)
    browser.displaySelectionButtons = NO; // Whether selection buttons are shown on each image (defaults to NO)
    browser.zoomPhotosToFill = YES; // Images that almost fill the screen will be initially zoomed to fill (defaults to YES)
    browser.alwaysShowControls = NO; // Allows to control whether the bars and controls are always visible or whether they fade away to show the photo full (defaults to NO)
    browser.enableGrid = YES; // Whether to allow the viewing of all the photo thumbnails on a grid (defaults to YES)
    browser.startOnGrid = NO;
    
    [browser setCurrentPhotoIndex:button.tag];
    
    // Present
    //    [self.dynamic_view_controller.navigationController pushViewController:browser animated:YES];
    
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:browser];
    nc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:nc animated:YES completion:nil];
}

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return [mw_url_array count];
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < [mw_url_array count])
        return [mw_url_array objectAtIndex:index];
    return nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 *  计算文本的宽高
 *
 *  @param str     需要计算的文本
 *  @param font    文本显示的字体
 *  @param maxSize 文本显示的范围
 *
 *  @return 文本占用的真实宽高
 */
- (CGSize)sizeWithString:(NSString *)str font:(UIFont *)font maxSize:(CGSize)maxSize
{
    NSDictionary *dict = @{NSFontAttributeName : font};
    // 如果将来计算的文字的范围超出了指定的范围,返回的就是指定的范围
    // 如果将来计算的文字的范围小于指定的范围, 返回的就是真实的范围
    CGSize size =  [str boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
    
    return size;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
